<template>
  <div>
    <el-upload
      v-show="!isShowProgress"
      action="#"
      :on-preview="handlePictureCardPreview"
      list-type="picture-card"
      :file-list="fileList"
      :http-request="onRequest"
      :on-change="onChange"
      :class="{ display: fileList.length }"
      :on-remove="onRemove"
      :before-upload="beforeUpload"
      accept="image/png,image/jpeg,image/gif"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress v-if="isShowProgress" type="circle" :percentage="percentage" />
    <!-- .sync -->
    <!-- :visible="dialogVisible" -->
    <!-- @update:visible.sync="dialogVisible =$event" -->
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
console.log(COS)
// 账号 api 密钥
// id : AKID2tYwGK8gyziBNIvHMAgvvd4F9m8C9sLW
// key : vay6wVoqc8NL2SbU6RWKyKQG7hz0kERO
const cos = new COS({
  SecretId: 'AKID2tYwGK8gyziBNIvHMAgvvd4F9m8C9sLW',
  SecretKey: 'vay6wVoqc8NL2SbU6RWKyKQG7hz0kERO'
})
console.log(cos)
export default {
  name: 'UploadImage',
  data() {
    return {
      fileList: [
        // { name: '默认图片', url: 'http://destiny001.gitee.io/image/zxc.gif', uid: 99559 }
      ],
      dialogVisible: false,
      dialogImageUrl: '', // 预览的图片地址
      currentUid: '',
      percentage: 0,
      isShowProgress: false
    }
  },

  created() {},

  methods: {
    // 点击删除
    onRemove(file, fileList) {
      // this.fileList = this.fileList.filter(item => item.uid !== file.uid)
      this.fileList = fileList
    },
    // 自定义上传
    onRequest(data) {
      cos.putObject(
        {
          Bucket: 'hr-sass-zy-1307760765' /* 必须 */,
          Region: 'ap-shanghai' /* 存储桶所在地域，必须字段 */,
          Key: data.file.name /* 必须 */,
          StorageClass: 'STANDARD',
          Body: data.file, // 上传文件对象
          onProgress: progressData => {
            // console.log(JSON.stringify(progressData))
            this.percentage = progressData.percent * 100
          }
        },
        (err, data) => {
          if (err) {
            this.$message.error('上传失败,请重新上传')
            this.isShowProgress = false
            this.fileList = this.fileList.filter(item => item.uid !== this.currentUid)
          }
          // console.log(err || data)
          if (!err && data.statusCode === 200) {
            const url = 'https://' + data.Location
            const index = this.fileList.findIndex(item => {
              return item.uid === this.currentUid
            })
            this.fileList[index].url = url
            // 通过 $emit 将数据传到父组件
            // this.fileList 表示上传的所有图片的一个数组
            // url 表示最新上传的一张
            this.$emit('on-success', this.fileList, url)
            this.isShowProgress = false
          }
        }
      )
    },
    // 本地上传成功
    onChange(file, fileList) {
      this.fileList = fileList
    },
    // 点击预览图片
    handlePictureCardPreview(file) {
      // console.log('点击预览')
      this.dialogVisible = true
      this.dialogImageUrl = file.url
    },
    // 点击图片上传之前
    beforeUpload(file) {
      // 第二种格式话图片的方法
      // const type = ['image/png', 'image/jpeg', 'image/gif']
      // if (file.type) {
      //   this.$message.error('亲,请选择格式正确的图片')
      // }
      const maxSize = 3 * 1021 * 1024 // 限制 1MB
      if (file.size >= maxSize) {
        this.$message.error('亲,请选择1MB以内的图片')
        return false
      }
      this.currentUid = file.uid
      this.isShowProgress = true
      return true
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .display .el-upload--picture-card {
  display: none;
}
// .el-progress {
//   width: 147px;
//   height: 147px;
//   position: relative;
//   top: -160px;
//   left: 10px;
//   background-color: rgba(255, 255, 255, 0.8);
// }
</style>
